package com.example.luyennghe;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
	private Button btnDsBainghe;
	private ProgressDialog pDialog;
	private UserInfo user = new UserInfo();
	private String urlGetCapdo = "http://huynh.cu.cc/android-server/get_capdo.php";
    private String urlGetDanhMuc = "http://huynh.cu.cc/android-server/get_danhmuc_baitest.php";
	private JSONParser jParser = new JSONParser();
	private Bundle extras;
	private String capdo = "1";
	private JSONArray JSarrayCapDo = new JSONArray();
	private ArrayList<CharSequence> listCapDo = new ArrayList<CharSequence>();
	private ArrayList<CharSequence> listDanhMuc = new ArrayList<CharSequence>();

	private static final String TAG_SUCCESS = "success";
	private static final String TAG_MESSAGE = "message";
	private static final String TAG_ARRAYCAPDO = "arraycapdo";
	private static final String TAG_CAPDO = "capdo";
    private static final String TAG_DANHMUC = "danhmuc";
    private static final String TAG_ARRAYDANHMUC = "arraydanhmuc";
	
	private boolean getCapDo_Success = false;
    private boolean error_Connect_Database = false;
    private boolean koTimThayDuLieu = false;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		extras = getIntent().getExtras();		
		user = (UserInfo)extras.getSerializable("userinfo");
		Log.d("userinfo", user.getUsername());
		btnDsBainghe = (Button)findViewById(R.id.btndsbainghe);
		File folder = new File(Environment.getExternalStorageDirectory().toString()+"/bainghe");
		folder.mkdirs();
		btnDsBainghe.setOnClickListener(dsBainghe);   
        if(checkInternetConnection()){
            getDataHandler();
        }
        else{
            Toast.makeText(getApplicationContext(), "Không có kết nối internet. Xin hãy thử lại", Toast.LENGTH_SHORT).show();
        }
	}
	
	//handler lay du lieu tu server
	public void getDataHandler(){
		final GetData getData = new GetData();
		try{        	
			getData.execute();
			Handler _handler = new Handler();
			_handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					if (getData.getStatus() == AsyncTask.Status.RUNNING) {
						getData.cancel(true);
						AlertDialog.Builder builder = new AlertDialog.Builder(
								MainActivity.this);
						builder.setMessage(
								"Kết nối quá thời gian... Xin hãy thử lại.")
								.setCancelable(false)
								.setIcon(R.drawable.warning_icon)
								.setTitle("Lỗi")
								.setPositiveButton("OK",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												dialog.dismiss();
												finish();
											}
										});
						AlertDialog alert = builder.create();
						alert.show();
					}

				}
			}, 30000); // timeout sau...giây sẽ hiện thông báo không kết nối
						// được.
		}
        catch (Exception ex)
        {
        	AlertDialog.Builder builder = new AlertDialog.Builder(
        			MainActivity.this);
			builder.setMessage(
					"Không thể tải dữ liệu từ server. Xin hãy thử lại.")
					.setCancelable(false)
					.setTitle("Lỗi")
					.setIcon(R.drawable.warning_icon)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(
										DialogInterface dialog,
										int id) {
									dialog.dismiss();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
        }       
	}
	Button.OnClickListener dsBainghe = new OnClickListener() {
		
		public void onClick(View v) {
			capdo = "1";
			// TODO Auto-generated method	
			final CharSequence[] capDo = listCapDo.toArray(new CharSequence[listCapDo.size()]);
			AlertDialog.Builder alt_bld = new AlertDialog.Builder(MainActivity.this);
			alt_bld.setIcon(R.drawable.check);
			alt_bld.setTitle("Chọn cấp độ");
			alt_bld.setSingleChoiceItems(capDo, 0,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int selected) {
							capdo =String.valueOf(selected + 1);
						}
					});
			alt_bld.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					Intent dsbn = new Intent(MainActivity.this, DsBaiNgheActivity.class);
					dsbn.putExtra("userinfo", user);
					dsbn.putExtra("capdo", capdo);
					startActivity(dsbn);
				}
			});
			alt_bld.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});

			AlertDialog alert = alt_bld.create();
			alert.show();
		}
	};
	
	
	class GetData extends AsyncTask<String, String, String> {
		 
        @Override
        protected void onPreExecute() {
            super.onPreExecute();     
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Đang tải cấp độ bài nghe. Vui lòng đợi...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        protected String doInBackground(String... args) {
            getCapDo();
            getDanhmuc();
			return null;
        }
         
        protected void onPostExecute(String file_url) {
            // updating UI from Background Thread
        	pDialog.dismiss();
        	if(getCapDo_Success){
        		getCapDo_Success = false;
				//Toast.makeText(getApplicationContext(), "Đã tải cấp độ", Toast.LENGTH_SHORT).show();
        	}
        	else 
        		if(koTimThayDuLieu)
        		{
        			koTimThayDuLieu = false;
        			Toast.makeText(getApplicationContext(), "Không tìm thấy dữ liệu", Toast.LENGTH_SHORT).show();
        		}
        		else
	        		if (error_Connect_Database) {
					error_Connect_Database = false;
					Toast.makeText(getApplicationContext(), "Không thể kết nôi đến database", Toast.LENGTH_SHORT).show();
				}
		}
	}
	
	class GetDanhMuc extends AsyncTask<String, String, String> {
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();     
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Đang tải cấp độ bài nghe. Vui lòng đợi...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        protected String doInBackground(String... args) {
          //lay cap do
            List<NameValuePair> paramsGetcapdo = new ArrayList<NameValuePair>();
            paramsGetcapdo.add(new BasicNameValuePair("request", "get_capdo"));  
            JSONObject json = new JSONObject();
            // getting JSON string from URL
            try {               
                json = jParser.makeHttpRequest(urlGetCapdo, "GET",
                        paramsGetcapdo);
                Log.d("getcapdo: ", json.toString());
                // Check SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
                String mes = json.getString(TAG_MESSAGE);
                if (success == 1 && mes.equals("OK")) {
                    getCapDo_Success = true;
                    JSarrayCapDo = json.getJSONArray(TAG_ARRAYCAPDO);
                    for (int i = 0; i < JSarrayCapDo.length(); i++) {
                        JSONObject c = JSarrayCapDo.getJSONObject(i);
                        // Storing each json item in variable
                        String temp = "Cấp độ " + String.valueOf(c.getInt(TAG_CAPDO));
                        File folder = new File(Environment.getExternalStorageDirectory().toString()+"/bainghe/" + String.valueOf(c.getInt(TAG_CAPDO)));
                        folder.mkdirs();
                        listCapDo.add(temp);
                    }
                }
                else
                    if(success==0 && mes.equals("Khong tim thay cap do"))
                        koTimThayDuLieu = true;
                    else
                        error_Connect_Database = true;
            } 
            catch (Exception ex) {
                Toast.makeText(getApplicationContext(), "Có lỗi xảy ra. " + ex.toString(), Toast.LENGTH_SHORT).show();
            }
            
            //lay danh muc
            List<NameValuePair> paramsGetDanhmuc = new ArrayList<NameValuePair>();
            paramsGetDanhmuc.add(new BasicNameValuePair("request", "get_danhmuc"));  
            json = new JSONObject();
            // getting JSON string from URL
            try {               
                json = jParser.makeHttpRequest(urlGetDanhMuc, "GET",
                        paramsGetDanhmuc);
                Log.d("getdanhmuc: ", json.toString());
                // Check SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
                String mes = json.getString(TAG_MESSAGE);
                if (success == 1 && mes.equals("OK")) {
                    getCapDo_Success = true;
                    JSarrayCapDo = json.getJSONArray(TAG_ARRAYCAPDO);
                    for (int i = 0; i < JSarrayCapDo.length(); i++) {
                        JSONObject c = JSarrayCapDo.getJSONObject(i);
                        // Storing each json item in variable
                        String temp = String.valueOf(c.getString(TAG_DANHMUC));                        
                        listDanhMuc.add(temp);
                    }
                }
                else
                    if(success==0 && mes.equals("Khong tim thay danh muc"))
                        koTimThayDuLieu = true;
                    else
                        error_Connect_Database = true;
            } 
            catch (Exception ex) {
                Toast.makeText(getApplicationContext(), "Có lỗi xảy ra. " + ex.toString(), Toast.LENGTH_SHORT).show();
            }
            return null;
        }
         
        protected void onPostExecute(String file_url) {
            // updating UI from Background Thread
            pDialog.dismiss();
            if(getCapDo_Success){
                getCapDo_Success = false;
                //Toast.makeText(getApplicationContext(), "Đã tải cấp độ", Toast.LENGTH_SHORT).show();
            }
            else 
                if(koTimThayDuLieu)
                {
                    koTimThayDuLieu = false;
                    Toast.makeText(getApplicationContext(), "Không tìm thấy dữ liệu", Toast.LENGTH_SHORT).show();
                }
                else
                    if (error_Connect_Database) {
                    error_Connect_Database = false;
                    Toast.makeText(getApplicationContext(), "Không thể kết nôi đến database", Toast.LENGTH_SHORT).show();
                }
        }
    }
	
	private boolean checkInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        // kiểm tra kết nối wifi và mobile(3G)
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    return true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    return true;
        }
        if (cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().isAvailable()
                && cm.getActiveNetworkInfo().isConnected()) {
            return true;
        }
        return false;
    }
	
	//lay danh sach cap do bai nghe
	public void getCapDo(){
	    List<NameValuePair> paramsGetcapdo = new ArrayList<NameValuePair>();
        paramsGetcapdo.add(new BasicNameValuePair("request", "get_capdo"));  
        JSONObject json = new JSONObject();
        // getting JSON string from URL
        try {               
            json = jParser.makeHttpRequest(urlGetCapdo, "GET",
                    paramsGetcapdo);
            Log.d("getcapdo: ", json.toString());
            // Check SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);
            String mes = json.getString(TAG_MESSAGE);
            if (success == 1 && mes.equals("OK")) {
                getCapDo_Success = true;
                JSarrayCapDo = json.getJSONArray(TAG_ARRAYCAPDO);
                for (int i = 0; i < JSarrayCapDo.length(); i++) {
                    JSONObject c = JSarrayCapDo.getJSONObject(i);
                    // Storing each json item in variable
                    String temp = "Cấp độ " + String.valueOf(c.getInt(TAG_CAPDO));
                    File folder = new File(Environment.getExternalStorageDirectory().toString()+"/bainghe/" + String.valueOf(c.getInt(TAG_CAPDO)));
                    folder.mkdirs();
                    listCapDo.add(temp);
                }
            }
            else
                if(success==0 && mes.equals("Khong tim thay cap do"))
                    koTimThayDuLieu = true;
                else
                    error_Connect_Database = true;
        } 
        catch (Exception ex) {
            Toast.makeText(getApplicationContext(), "Có lỗi xảy ra. " + ex.toString(), Toast.LENGTH_SHORT).show();
        }
	}
	
	//lay danh sach danh muc bai test
	public void getDanhmuc(){
        List<NameValuePair> paramsGetDanhmuc = new ArrayList<NameValuePair>();
        paramsGetDanhmuc.add(new BasicNameValuePair("request", "get_danhmuc"));  
        JSONObject json = new JSONObject();
        // getting JSON string from URL
        try {               
            json = jParser.makeHttpRequest(urlGetDanhMuc, "GET",
                    paramsGetDanhmuc);
            Log.d("getdanhmuc: ", json.toString());
            // Check SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);
            String mes = json.getString(TAG_MESSAGE);
            if (success == 1 && mes.equals("OK")) {
                getCapDo_Success = true;
                JSarrayCapDo = json.getJSONArray(TAG_ARRAYDANHMUC);
                for (int i = 0; i < JSarrayCapDo.length(); i++) {
                    JSONObject c = JSarrayCapDo.getJSONObject(i);
                    // Storing each json item in variable
                    String temp = String.valueOf(c.getString(TAG_DANHMUC));                        
                    listDanhMuc.add(temp);
                }
            }
            else
                if(success==0 && mes.equals("Khong tim thay danh muc"))
                    koTimThayDuLieu = true;
                else
                    error_Connect_Database = true;
        } 
        catch (Exception ex) {
            Toast.makeText(getApplicationContext(), "Có lỗi xảy ra. " + ex.toString(), Toast.LENGTH_SHORT).show();
        }
	}
}
	
	
